package com.topone.permission.sercurity.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.topone.permission.entity.Permission;
import com.topone.permission.entity.SysUser;
import com.topone.permission.model.UserSeesion;
import com.topone.permission.service.PermissionService;
import com.topone.permission.service.SysUserService;

/**
 * 查询用户信息
 * @author XiaZhentao
 * @date 2018年12月1日
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	
	@Autowired
	SysUserService sysUserService;
	
	@Autowired
	PermissionService permissionService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user = sysUserService.findByPhone(username);
		if(Objects.isNull(user)){
			throw new UsernameNotFoundException("用户名或密码错误");
		}
		List<Permission> permissions = permissionService.getPermissionByUserId(user.getUserId());
		List<GrantedAuthority> grantedAuthorities = new ArrayList <>();
        for (Permission permission : permissions) {
            if (permission != null && permission.getName()!=null) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_"+permission.getName());
            //1：此处将权限信息添加到 GrantedAuthority 对象中，
            	//在后面进行全权限验证时会使用GrantedAuthority 对象。
            grantedAuthorities.add(grantedAuthority);
            }
        }
        return new UserSeesion(user.getHandPhone(), user.getPassword(), user.getCompanyCode(),user.getUserId(),grantedAuthorities);
	}

}
